package com.fm.webrtc.websocket;

import android.util.Log;

import com.fm.webrtc.websocket.message.callback.CallWebSocketMessage;
import com.fm.webrtc.websocket.message.Message;
import com.fm.webrtc.websocket.message.MessageUtil;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocketListener;

public class WebSocket {
    private final static String TAG = WebSocket.class.getSimpleName();
    private okhttp3.WebSocket webSocket;
    private OkHttpClient okHttpClient;
    private String roomId = "fm";
    private String peerId = "";
    private Request request;
    private CallWebSocketMessage callWebSocketMessage;

    public WebSocket(CallWebSocketMessage callWebSocketMessage){
        this.callWebSocketMessage = callWebSocketMessage;
    }

    public void close(){
        try{
            if (webSocket != null) {
                webSocket.close(1000, "User-initiated close");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public<T> void send(String messageType, T data){
        this.webSocket.send(MessageUtil.encoder(messageType, data));
    }

    public void request(String url){
        this.okHttpClient = new OkHttpClient();

        this.request = new Request.Builder()
                .url(url)
                .build();

        this.webSocket = this.okHttpClient.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(okhttp3.WebSocket webSocket, Response response) {
                // WebSocket 连接成功打开时的回调
                Log.e(TAG, response.toString());
                callWebSocketMessage.open();
            }

            @Override
            public void onMessage(okhttp3.WebSocket webSocket, String text) {
                // 收到 WebSocket 文本消息时的回调
                Message<JsonObject> message = MessageUtil.decoder(text, new TypeToken<Message<JsonObject>>() {
                }.getType());
                callWebSocketMessage.receiveMessage(message);
            }

            @Override
            public void onClosing(okhttp3.WebSocket webSocket, int code, String reason) {
                // WebSocket 正在关闭时的回调
            }

            @Override
            public void onClosed(okhttp3.WebSocket webSocket, int code, String reason) {
                // WebSocket 关闭后的回调
            }

            @Override
            public void onFailure(okhttp3.WebSocket webSocket, Throwable t, Response response) {
                // WebSocket 连接失败时的回调
                t.printStackTrace();
            }
        });
        webSocket.request();
    }

}
